package com.example.shopping.service;


import com.example.shopping.dto.CartItem;
import com.example.shopping.dto.OrderItem;
import com.example.shopping.entity.Address;
import com.example.shopping.entity.Goods;
import com.example.shopping.entity.Order;
import com.example.shopping.mapper.OrderMapper;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class OrderService {
    @Autowired
    CartService cartService;
    @Autowired
    AddressService addressService;
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    AlipayService alipayService;
    @Autowired
    GoodsService goodsService;
    //生成订单
    public String submitOrder(Integer userId, Integer addressId, String telphone, String payType, HttpSession session) {
        List<CartItem> cartItems = cartService.getCar(userId);
        if (cartItems == null || cartItems.isEmpty()) {
            return null;
        }
        //获取地址信息
        Address address = addressService.getAddressById(addressId);
        if (address == null) {
            return null;
        }

        // 1. 生成订单编号
        String orderNo = userId + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        Double totalMoney = cartService.getTotalPrice(userId);
        // 2. 插入wn_order
        Order order = new Order();
        order.setNo(orderNo);
        order.setAddTime(new Date());
        order.setUserId(userId);
        order.setTotalMoney(totalMoney);
        order.setAddress(address.getProvince() + address.getCity() + address.getArea() + address.getStreet());
        order.setAccept(address.getAccept());
        order.setTelphone(telphone);
        order.setPayType(payType);
        order.setStatus("N"); // 未支付
        orderMapper.insertOrder(order); // 需返回自增id

        // 3. 插入wn_order_item
        for (CartItem item : cartItems) {
            OrderItem orderItem = new OrderItem();
            orderItem.setOrderId(order.getId());
            orderItem.setGoodsId(item.getGoodid());
            orderItem.setName(item.getGoodname());
            orderItem.setImage(item.getGoodimage());
            orderItem.setPrice(item.getGoodprice());
            orderItem.setNum(item.getNum());
            orderMapper.insertOrderItem(orderItem);
        }
        return orderNo;
    }
    //让支付宝处理
    @Transactional
    public String payOrder(Integer userId, String orderId,HttpSession session) {
        //1.购物车里是否有数据
        List<CartItem> cartItems = cartService.getCar(userId);
        if (cartItems == null || cartItems.isEmpty()) {
            return null;
        }
        //2.判断库存
        for(CartItem item : cartItems){
            //判断库存
            Goods good = goodsService.findById(item.getGoodid());
            if(item.getNum() > good.getStock()){
                return  "fail:stock";
            }
        }
        //获取支付金额
        Double totalMoney = cartService.getTotalPrice(userId);
        //接入支付宝：
        String form = alipayService.createPayment(orderId, ""+totalMoney, "支付订单号:"+orderId);
        //保存订单id
        session.setAttribute("orderId",orderId);
        return form;
    }
    //支付宝流程结束后更新数据库的订单以及清空购物车
    public String orderSuccess(String orderId, Integer userId) {
        //支付成功后继续处理
        //获取购物车数据
        List<CartItem> cartItems = cartService.getCar(userId);
        //3. 修改商品库存
        for (CartItem item : cartItems) {
            goodsService.reduceStock(item.getGoodid(), item.getNum());
        }
        //清理购物车
        cartService.clearCar(userId);
        // 更新订单状态
        this.updateOrderStatus(orderId, "3", new Date());
        return "success";
    }

    private void updateOrderStatus(String orderId, String status, Date date) {
        System.out.println("更新订单状态");
        System.out.println("订单号: " + orderId);
        System.out.println("状态: " + status);
        System.out.println("时间: " + date);
        boolean b = orderMapper.updateOrderStatus(orderId,status,date);
        if (b) {
            System.out.println("更新成功");
        } else {
            System.out.println("更新失败");
        }
    }

    public List<OrderItem> getOrder(Integer userId) {
        return  orderMapper.getOrder(userId);
    }
}
